package com.parking.bang.rpc.core.server;

import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.commons.lang3.reflect.MethodUtils;

import com.parking.bang.rpc.model.ReqMessage;
import com.parking.bang.rpc.model.RespMessage;

/**
 * Init Request, respose and call methods
 * 
 * @author ivan
 *
 */
public class MessageRecvInitializeTask implements Callable<Boolean> {

	private ReqMessage request = null;
	private RespMessage response = null;
	private Map<String, Object> handlerMap = null;

	MessageRecvInitializeTask(ReqMessage request, RespMessage response, Map<String, Object> handlerMap) {
		this.request = request;
		this.response = response;
		this.handlerMap = handlerMap;
	}

	public Boolean call() throws Exception {
		response.setMessId(request.getMessId());
		try {
			Object result = reflect(request);
			response.setResult(result);
			return Boolean.TRUE;
		} catch (Throwable t) {
			response.setErrCode(t.toString());
			t.printStackTrace();
			System.err.printf("RPC Server invoke error!\n");
			return Boolean.FALSE;
		}
	}

	private Object reflect(ReqMessage request) throws Throwable {
		String className = request.getClzName();
		Object serviceBean = handlerMap.get(className);
		String methodName = request.getMethodName();
		Object[] parameters = request.getParas();
		return MethodUtils.invokeMethod(serviceBean, methodName, parameters);
	}

	public ReqMessage getRequest() {
		return request;
	}

	public void setRequest(ReqMessage request) {
		this.request = request;
	}

	public RespMessage getResponse() {
		return response;
	}

	public void setResponse(RespMessage response) {
		this.response = response;
	}

}
